package com.polaris.live.dialog_fragment

import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.R
import com.polaris.live.adapter.RoomInvitationAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupRoomInvitationBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.resp.back_resp.LiveInviteJoinUserResp
import com.polaris.live.translation.R.string
import com.polaris.live.ui.message.fragment.dialog.BottomDialogFragment
import com.polaris.live.viewmodel.RoomInvitationModel
import com.polaris.live.widget.refresh.ListOperator
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * RoomInvitationFragmentDialog房间邀请
 *
 * @author Created by 天晴 on 2024/11/27/009 11:12
 */
class RoomInvitationFragmentDialog : BottomDialogFragment() {

    private val mLiveId by lazy { arguments?.getLong("liveId") ?: -1 }

    private lateinit var mBinding: PopupRoomInvitationBinding

    private val mViewModel by viewModels<RoomInvitationModel>()

    override val isReusable: Boolean = false

    private var mListOperator: ListOperator<LiveInviteJoinUserResp>? = null

    private val mAdapter by lazy { RoomInvitationAdapter() }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .navigationBarDarkIcon(false)
            .init()
    }

    override fun setStyle() {
        setStyle(STYLE_NO_FRAME, R.style.DialogFragmentBottomGiftDialog)
    }

    override fun getDialogHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        return PopupRoomInvitationBinding.inflate(inflater, container, false).let {
            mBinding = it
            it.root
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel.setLiveId(mLiveId)

        mBinding.recyclerView.setEnableRefresh(false)
        mBinding.recyclerView.setEmptyTip(
            R.drawable.family_empty,
            getString(string.no_friends)
        )
        mBinding.recyclerView.apply {
            recycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            recycler.itemAnimator = null
            mListOperator = attachedAdapter(mAdapter, mViewModel)
            mListOperator?.observe(
                this@RoomInvitationFragmentDialog,
                mViewModel.followersLiveData
            )
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.invite_rl -> {
                    mAdapter.getItemOrNull(position)?.let {
                        mViewModel.inviteJoin(it.user.userId, position)
                    }
                }

                R.id.ok_rl -> {
                    ToastGravity.showGravity(StringUtils.getString(string.you_already_invited_invitation))

                }
            }
        }
        initListener()
        mViewModel.onRefresh()
    }

    private var searchJob: Job? = null
    private fun initListener() {
        //关闭直播监听
        mViewModel.inviteJoinLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(StringUtils.getString(string.invitation_successful))
                mAdapter.getItemOrNull(it)?.apply {
                    invited = true
                }
                mAdapter.notifyItemChanged(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        mBinding.searchEdit.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                val searchString = mBinding.searchEdit.text.toString()
                if (searchString.isEmpty()) {
                    mListOperator?.resetData()
                    mViewModel.searchUser(null)
                    searchJob?.cancel()
                    searchJob = null
                } else {
                    searchJob?.cancel()
                    searchJob = mViewModel.viewModelScope.launch {
                        try {
                            delay(500)  // 延迟500
                            mViewModel.searchUser(searchString)
                        } finally {
                            if (searchJob == coroutineContext[Job]) {
                                searchJob = null
                            }
                        }
                    }
                }
            }
        })

        mBinding.editClear.setOnSingleClickListener {
            mBinding.searchEdit.text = Editable.Factory.getInstance().newEditable("")
        }
        mBinding.mainLl.setOnSingleClickListener {
        }
        mBinding.framelayout.setOnSingleClickListener {
            hide()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        searchJob?.cancel()
        searchJob = null
    }
}

